package com.voxel.sense.infomsg.module.trace.map;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.example.com.common.utils.constants.TimeConstants;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ClockInMarkerBean;
import com.voxel.sense.infomsg.utils.GPSUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.PeopleTranceEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.NetHelper;

/**
 * Created by ChenYiYao on 2018/5/21.
 */
public class CheckinsRecordPresenter extends BasePresenter<CheckinsRecordContract.View>
        implements CheckinsRecordContract.Presenter, DataSource.Callback<BaseEntity> {
    boolean isLoadingDate = false;
    private boolean mIsShowWinow = false;
    String mUserId;
    private List<String> mDates;//打卡事件数据集
    private String mUserName;


    public CheckinsRecordPresenter(CheckinsRecordContract.View view) {
        super(view);
    }


    @Override
    public void doLaodData(String date) {
        if (!NetworkUtils.isConnected()) {
            mView.showError(Factory.app().getString(R.string.network_unavailable));
            return;
        }

        if (TextUtils.isEmpty(date)) return;
        try {
            mView.showLoading("", false);
            //TODO：控件滑动过快时，选择会拿到空的时间
            Date startTime = TimeUtils.getDate(date, new SimpleDateFormat("yyyyMMdd"), 0, TimeConstants.SEC);
            Date endTime = new Date();
            endTime.setTime(startTime.getTime());
            endTime.setDate(startTime.getDate() + 1);

            NetHelper.getUserTrack(this, mUserId, startTime.getTime(), endTime.getTime() - 1000);
        } catch (Exception e) {
            e.printStackTrace();
            mView.dimissLoading();
        }

    }

    @Override
    public void doLoadDateList(String userId, String userName, boolean isShowWinow) {
        if (!NetworkUtils.isConnected() || isLoadingDate == true)
            return;
        mView.showLoading("");
        this.mUserId = userId;
        mIsShowWinow = isShowWinow;
        mUserName = userName;
        isLoadingDate = true;
        NetHelper.getUserTrackDate(this, userId);
    }

    @Override
    public void doHandlerClockBean(List<ClockInMarkerBean> beans) {
        int i = 1;
        ArrayList<MarkerOptions> options = new ArrayList<>();
        ArrayList<LatLng> lngArrayList = new ArrayList<>();
        for (ClockInMarkerBean bean : beans) {
            LatLng latLng = new LatLng(bean.latitude, bean.longitude);
            lngArrayList.add(latLng);

            View view = View.inflate((Context) mView, R.layout.map_custom_marker, null);
            TextView textView = view.findViewById(R.id.tv_numb);
            textView.setText("" + i);
            i++;
            String desc = String.format(Factory.app().getString(R.string.user_name_id), mUserName, mUserId);
            MarkerOptions draggable = new MarkerOptions()
                    .position(latLng)
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromView(view))
                    .title(bean.mTime)
                    .snippet(desc);

            options.add(draggable);

        }
        //添加marker前，先清除之前的数据
        mView.onCleanMap();
        mView.onAddMarker(options);
        mView.onDrawLine(lngArrayList);
    }

    @Override
    public void onDataLoaded(BaseEntity data, int reqId) {
        if (mView == null)
            return;

        mView.dimissLoading();
        switch (reqId) {
            case RequestIdFactory.CLOCK_IN_DATE: //打卡时间列表
                isLoadingDate = false;
                List<String> bean = (List<String>) data.getData();
                if (data.isSuccess() && bean != null && bean.size() > 0) {
                    mDates = bean;
                    handlerDateList(bean);//组装数据
                    if (mIsShowWinow) mView.onShowDateList();//显示窗口
                    mIsShowWinow = false;
                } else {
                    mView.showError(Factory.app().getString(R.string.no_clock_in_record));
                    mIsShowWinow = false;
                    isLoadingDate = false;
                }
                break;
            case RequestIdFactory.CLOCK_IN_LOCATION:
                final List<PeopleTranceEntity> traceBean = (List<PeopleTranceEntity>) data.getData();
                if (data.isSuccess() && traceBean != null && traceBean.size() > 0) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            parsingData(traceBean);
                        }
                    }).start();

                }
                break;
        }
    }

    private void handlerDateList(List<String> bean) {
        Map<String, String> yearMap = new LinkedHashMap<>();
        Map<String, LinkedHashMap<String, String>> YMonthMap = new LinkedHashMap<>();
        Map<String, LinkedHashMap<String, String>> YMDayMap = new LinkedHashMap<>();
        ArrayList<ArrayList> mm = new ArrayList<>();
        for (String str : bean) {
            String[] split = str.split("-");
            String y = split[0];
            String m = split[1];
            String d = split[2];

            //添加年份
            String ListY = yearMap.get(y);
            if (TextUtils.isEmpty(ListY)) {
                //该年份未添加，则当前时间是未添加过的
                yearMap.put(y, y);
            }

            //添加月份
            LinkedHashMap<String, String> monthHas = YMonthMap.get(y);
            if (monthHas == null) {
                //该年份的月份未添加
                monthHas = new LinkedHashMap<>();
                monthHas.put(m, m);
                YMonthMap.put(y, monthHas);
            } else {
                monthHas.put(m, m);
            }

            //添加日期
            LinkedHashMap<String, String> dayhas = YMDayMap.get(y + m);
            if (dayhas == null) {
                //该年份的月份未添加
                dayhas = new LinkedHashMap<>();
                dayhas.put(d, d);
                YMDayMap.put(y + m, dayhas);
            } else {
                dayhas.put(d, d);
            }
        }

        //再次组装数据，组装为树形3级结构
        Set<String> strings = yearMap.keySet();
        List<String> yearList = new ArrayList<>();
        List<List<String>> monthList = new ArrayList<>();
        List<List<ArrayList<String>>> daysList = new ArrayList<>();
        for (String year : strings) {
            HashMap<String, String> month = YMonthMap.get(year);
            if (month != null && month.size() > 0) {
                //添加年
                yearList.add(year);
                List ymList = new ArrayList();
                List ymdList = new ArrayList();
                Set<String> monKey = month.keySet();
                //遍历月份
                for (String monStr : monKey) {
                    HashMap<String, String> days = YMDayMap.get(year + monStr);
                    if (days != null && days.size() > 0) {
                        ymList.add(monStr);//添加该年份的月数据
                        List mday = new ArrayList();
                        //遍历日期
                        Set<String> daykey = days.keySet();
                        for (String dayStr : daykey) {
                            //TODO:
                            mday.add(dayStr);
                        }
                        ymdList.add(mday);
                    }

                }
                monthList.add(ymList);
                daysList.add(ymdList);
            }
        }
        mView.onUpDateList(yearList, monthList, daysList, mDates);
    }


    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null)
            return;

        mView.dimissLoading();
        if (reqId == RequestIdFactory.CLOCK_IN_DATE) {
            isLoadingDate = false;
            mIsShowWinow = false;
            mView.showError("获取打卡时间记录失败");
        } else if (reqId == RequestIdFactory.CLOCK_IN_LOCATION) {
            ToastUtil.showToastLong(Factory.app(), strRes);
        }
    }


    //构造轨迹数据
    private void parsingData(List<PeopleTranceEntity> traceBean) {
        int i = 1;
        ArrayList<MarkerOptions> options = new ArrayList<>();
        ArrayList<LatLng> lngArrayList = new ArrayList<>();
        for (PeopleTranceEntity body : traceBean) {
            for (PeopleTranceEntity.CoordinateListBean bean : body.getCoordinateList()) {
                try {
                    String longitude = bean.getLongitude();
                    String latitude = bean.getLatitude();
                    double lon = Double.parseDouble(longitude);
                    double lat = Double.parseDouble(latitude);
                    long l = Long.parseLong(bean.getDataTime());
                    double[] doubles = GPSUtils.bd09_To_Gcj02(lat, lon);

                    String date = TimeUtils.getString(l, 0, TimeConstants.SEC);
                    LatLng latLng = new LatLng(doubles[0], doubles[1]);
                    lngArrayList.add(latLng);

                    View view = View.inflate((Context) mView, R.layout.map_custom_marker, null);
                    TextView textView = view.findViewById(R.id.tv_numb);
                    textView.setText("" + i);
                    i++;
                    String desc = String.format(Factory.app().getString(R.string.user_name_id), mUserName, mUserId);
                    MarkerOptions draggable = new MarkerOptions()
                            .position(latLng)
                            .draggable(false)
                            .icon(BitmapDescriptorFactory.fromView(view))
                            .title(date)
                            .snippet(desc);

                    options.add(draggable);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //添加marker前，先清除之前的数据
        mView.onCleanMap();
        mView.onAddMarker(options);
        mView.onDrawLine(lngArrayList);
    }

}


